package com.dream.cgomall.controller;

import com.dream.cgomall.entity.CgoActiveRedpackage;
import com.dream.cgomall.service.CgoRedPackageSevice;
import com.dream.cgomall.service.ServiceResult;
import com.dream.cgomall.vo.RedPackageInfoVO;
import com.dream.cgomallcore.util.DoDuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Controller
@RequestMapping("redRain")
public class RedRainController {
    @Autowired
    CgoRedPackageSevice redPackageSevice;
    @RequestMapping("addAtive")
    @ResponseBody
    public ServiceResult addAtive(@RequestBody CgoActiveRedpackage cgoActiveRedpackage){
        return redPackageSevice.addRedPackageAtive( cgoActiveRedpackage);
    }
    @RequestMapping("loadAtiveInfo")
    @ResponseBody
    public ServiceResult ativeInfo(Integer userId){
        try {
            ServiceResult<CgoActiveRedpackage> redpackage = redPackageSevice.getRedPackageInfo(userId);
            if (!redpackage.isSuccess() && redpackage.getResult()==null){
                return redpackage;
            }else{
                if(redpackage.getResult().getBeginTime().isAfter(LocalDateTime.now()) ){
                    LocalDateTime red= redpackage.getResult().getBeginTime();
                    Duration duration = Duration.between(LocalDateTime.now(),red);
                    return ServiceResult.of(new RedPackageInfoVO(redpackage.getResult(),false,DoDuration.doExce( duration.toSeconds())));
                }else{
                    LocalDateTime red= redpackage.getResult().getEndTime();
                    Duration duration = Duration.between(LocalDateTime.now(),red);
                    return ServiceResult.of(new RedPackageInfoVO(redpackage.getResult(),true, DoDuration.doExce( duration.toSeconds())));
                }
            }
        }catch (RuntimeException e){
            System.out.println(e);
            return  ServiceResult.notFound();
        }

    }
    @RequestMapping("collectRedPack")
    @ResponseBody
    public ServiceResult collectRedPack(Integer userId,Integer ActiveuserId){
        return redPackageSevice.collectionRedPackage(userId,ActiveuserId);
    }
    @RequestMapping("refresh")
    @ResponseBody
    public ServiceResult refresh(){
        return redPackageSevice.refreshActive();
    }
}
